import { customerApi } from '../lib/api';
import type { Customer } from '../types';

/**
 * 客户数据服务层
 * 提供高级的客户数据管理功能
 */
export class CustomerService {
  private static instance: CustomerService;
  private customers: Customer[] = [];
  private isInitialized = false;
  private isLoading = false;
  private lastFetchTime = 0;
  private readonly CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存

  private constructor() { }

  public static getInstance(): CustomerService {
    if (!CustomerService.instance) {
      CustomerService.instance = new CustomerService();
    }
    return CustomerService.instance;
  }

  /**
   * 获取所有客户
   */
  public async getAllCustomers(forceRefresh = false): Promise<Customer[]> {
    // 检查缓存
    if (this.isInitialized && !forceRefresh && (Date.now() - this.lastFetchTime) < this.CACHE_DURATION) {
      return this.customers;
    }

    // 如果正在加载，等待
    if (this.isLoading) {
      return new Promise((resolve) => {
        const checkLoaded = () => {
          if (!this.isLoading) {
            resolve(this.customers);
          } else {
            setTimeout(checkLoaded, 100);
          }
        };
        checkLoaded();
      });
    }

    // 开始加载
    this.isLoading = true;

    try {
      const response = await customerApi.getKycProfiles({
        page: 1,
        page_size: 100,
        use_pagination: false
      });

      if (response.success && response.data && Array.isArray(response.data.user_profiles)) {
        this.customers = response.data.user_profiles;
        this.isInitialized = true;
        this.lastFetchTime = Date.now();
      }

      return this.customers;
    } catch (error) {
      console.error('Failed to fetch customers:', error);
      return this.customers;
    } finally {
      this.isLoading = false;
    }
  }

  /**
   * 根据ID获取客户
   */
  public getCustomerById(customerId: string): Customer | null {
    return this.customers.find(customer =>
      customer.id.toString() === customerId
    ) || null;
  }

  /**
   * 根据姓名获取客户
   */
  public getCustomerByName(name: string): Customer | null {
    return this.customers.find(customer => customer.name === name) || null;
  }

  /**
   * 搜索客户
   */
  public searchCustomers(searchTerm: string, filters?: {
    riskLevel?: string;
    occupation?: string;
    investmentGoal?: string;
    minAssets?: number;
    maxAssets?: number;
  }): Customer[] {
    return this.customers.filter(customer => {
      // 搜索词匹配
      const matchesSearch = !searchTerm ||
        customer.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        customer.occupation?.toLowerCase().includes(searchTerm.toLowerCase());

      // 风险等级过滤
      const matchesRiskLevel = !filters?.riskLevel ||
        customer.risk_level === filters.riskLevel;

      // 职业过滤
      const matchesOccupation = !filters?.occupation ||
        customer.occupation?.includes(filters.occupation);

      // 投资目标过滤
      const matchesInvestmentGoal = !filters?.investmentGoal ||
        customer.investment_goal?.includes(filters.investmentGoal);

      // 资产范围过滤
      const matchesAssetRange = !filters?.minAssets && !filters?.maxAssets ||
        (customer.total_investment >= (filters.minAssets || 0) &&
          customer.total_investment <= (filters.maxAssets || Infinity));

      return matchesSearch && matchesRiskLevel && matchesOccupation &&
        matchesInvestmentGoal && matchesAssetRange;
    });
  }

  /**
   * 获取高优先级客户
   */
  public getHighPriorityCustomers(): Customer[] {
    return this.customers.filter(customer => {
      const riskLevel = customer.risk_level;
      return riskLevel?.includes('R4') || riskLevel?.includes('R5');
    });
  }

  /**
   * 刷新客户数据
   */
  public async refreshCustomers(): Promise<Customer[]> {
    return await this.getAllCustomers(true);
  }

  /**
   * 清空缓存
   */
  public clearCache(): void {
    this.customers = [];
    this.isInitialized = false;
    this.lastFetchTime = 0;
  }

  /**
   * 获取缓存状态
   */
  public getCacheStatus() {
    return {
      isInitialized: this.isInitialized,
      isLoading: this.isLoading,
      lastFetchTime: this.lastFetchTime,
      cacheAge: Date.now() - this.lastFetchTime,
      customerCount: this.customers.length
    };
  }

  /**
   * 初始化服务
   */
  public async initialize(): Promise<void> {
    if (!this.isInitialized) {
      await this.getAllCustomers();
    }
  }

  // 获取客户的WebSocket ID - 与ClientTestPage格式保持一致
  public getCustomerWebSocketId(customer: Customer | null): string | null {
    if (!customer?.id || !customer?.name) return null;
    return `C_${customer.id}_${customer.name.replace(/\s+/g, '_')}`;
  }
}

// 导出单例实例
export const customerService = CustomerService.getInstance(); 